﻿using Permission.DataModel;
using Permission.Repository;
using Permission.UnitOfWork;
using Permission.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Permission.Service.Impl
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleRepository _roleRepository;

        private IUnitOfWork _unitOfWork;

        public UserService(IUserRepository userRepository, IUserRoleRepository userRoleRepository, IRoleRepository roleRepository,
            IUnitOfWork unitOfWork)
        {
            _userRepository = userRepository;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            _unitOfWork = unitOfWork;
        }

        public ExecuteResult<UserModel> Sign(UserModel user)
        {
            var model = _userRepository.Entities().SingleOrDefault(m => m.UserName == user.UserName);
            if (model == null)
                return new ExecuteResult<UserModel> { Code = 1, Message = "用户不存在" };
            if (model.Password != user.Password)
                return new ExecuteResult<UserModel> { Code = 2, Message = "密码错误" };

            var roleIds = _userRoleRepository.Entities().Where(m => m.UserId == model.Id).Join(_roleRepository.Entities(), m => m.RoleId, n => n.Id, (m, n) => n.Id).ToList();

            return new ExecuteResult<UserModel>
            {
                Code = 0,
                Data = new UserModel
                {
                    Id = model.Id,
                    UserName = model.UserName,
                    Password = model.Password,
                    RealName = model.RealName,
                    Role = roleIds
                }
            };
        }

        public Sys_User LoadUser(string id)
        {
            return _userRepository.Entities().FirstOrDefault(s => s.Id == id);
        }

        public object Users()
        {
            return _userRepository.Entities().Take(10)
                .GroupJoin(_userRoleRepository.Entities(), a => a.Id, b => b.UserId, (a, b) =>
                    new
                    {
                        a.Id,
                        a.UserName,
                        a.RealName,
                        a.Password,
                        a.CreateDate,
                        a.Status,
                        Roles = b.Select(m => new { RoleName = m.RoleId })
                    }).ToList();
        }

        /// <summary>
        /// 添加、修改 User
        /// </summary>
        /// <param name="userModel"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public ExecuteResult SaveUser(UserModel userModel)
        {
            ExecuteResult result = new ExecuteResult();
            var userEntity = new Sys_User
            {
                UserName = userModel.UserName,
                Password = userModel.Password,
                RealName = userModel.RealName,
                CreateDate = DateTime.Now,
                Status = 1
            };

            if (string.IsNullOrEmpty(userModel.Id)) // 添加用户
            {
                userEntity.Id = Guid.NewGuid().ToString();
                _userRepository.Insert(userEntity);
            }
            else // 修改操作
            {
                userEntity.Id = userModel.Id;
                _userRepository.Update(m => new Sys_User
                {
                    Id = userEntity.Id,
                    UserName = userEntity.UserName,
                    RealName = userEntity.RealName,
                    Status = userEntity.Status
                });
                //删除用户角色关系
                var userRoleIdArray = _userRoleRepository.Entities()
                    .Where(m => m.UserId == userModel.Id).Select(s => s.Id).ToList();
                foreach (var roleId in userRoleIdArray)
                {
                    _userRoleRepository.Delete(new Sys_User_Role { Id = roleId });
                }
            }

            if (null != userModel.Role && userModel.Role.Any())
            {
                var userRoles = new List<Sys_User_Role>();
                foreach (var roleId in userModel.Role)
                {
                    userRoles.Add(new Sys_User_Role { Id = Guid.NewGuid().ToString(), UserId = userEntity.Id, RoleId = roleId });
                }
                //添加用户角色关系
                _userRoleRepository.Insert(userRoles);
            }

            result.Code = _unitOfWork.Commit() > 0 ? 0 : 1;
            return result;
        }

        public ExecuteResult DelUser(string id)
        {
            ExecuteResult result = new ExecuteResult();
            var userRoleIdArray = _userRoleRepository.Entities()
                    .Where(m => m.UserId == id).Select(s => s.Id).ToList();
            foreach (var roleId in userRoleIdArray)
            {
                _userRoleRepository.Delete(new Sys_User_Role { Id = roleId });
            }
            _userRepository.Delete(new Sys_User { Id = id });
            result.Code = _unitOfWork.Commit() > 0 ? 0 : 1;
            return result;
        }
    }
}
